#coding:utf-8
import time,os,uuid,json,sys
from app import db
from app.admin import admin
from flask import request, jsonify,session,g,current_app
from werkzeug.utils import secure_filename
from app.models import Article,ArticleSort,User,ArticleComment,ReplyComment
from app.func.token_auth import auth as http_auth
from response_code import RET
from error_msg import LoggerError

# sys._getframe().f_code.co_name   获取本行所在的函数名


# --------------------------文章后台接口----------------------------------------

#文章标签类型接口
@admin.route("/arc_sort",methods=["POST","GET"])
@http_auth.login_required
def get_arc_sort():
    if not g.user_id:
        current_app.logger.error(LoggerError.AUTHERROR)
        return jsonify(code=RET.REQERR,msg="无权请求此接口",data="")
    if request.method=="POST":
        arc_sort=request.get_json().get("arc_sort")
        if not arc_sort:
            current_app.logger.error(LoggerError.PARAMERROR)
            return jsonify(code=RET.PARAMERR, msg="参数错误")
        try:
            arc_sorts=db.session.query(ArticleSort).filter(ArticleSort.sort==arc_sort).first()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(code=RET.DBERR, msg="查询数据失败", data="")
        if arc_sorts:
            if arc_sorts.is_del==1:
                arc_sorts.is_del=0
                try:
                    db.session.commit()
                except Exception as e:
                    current_app.logger.error(e)
                    return jsonify(code=RET.DBERR, msg="添加文章分类失败", data="")
                return jsonify(code=RET.OK, msg="添加文章分成功", data="")
        if not arc_sorts:
            sort=ArticleSort(
                sort=arc_sort,
                addtime=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
            try:
                db.session.add(sort)
                db.session.commit()  # 提交
            except Exception as e:
                current_app.logger.error(e)
                return jsonify(code=RET.DBERR, msg="添加文章分类失败", data="")
            return jsonify(code=RET.OK, msg="添加文章分类成功", data="")
    else:
        try:
            arc_sorts = db.session.query(ArticleSort.id,ArticleSort.sort,ArticleSort.addtime).filter(ArticleSort.is_del==0).all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(code=RET.DBERR,msg="查询数据失败",data="")
        arc_sort_data = [{
                "id":arc_sort.id,
                "name":arc_sort.sort,
                "date":str(arc_sort.addtime)
            } for arc_sort in arc_sorts]
        return jsonify(code=RET.OK,msg="获取文章分类数据成功",arc_sort=arc_sort_data)


#修改文章标签类型接口
@admin.route("/change_arc_sort",methods=["POST"])
@http_auth.login_required
def change_arc_sort():
    if not g.user_id:
        current_app.logger.error(LoggerError.AUTHERROR)
        return jsonify(code=RET.REQERR,msg="无权请求此接口",data="")
    arc_sort=request.get_json().get("arc_sort")
    new_arc_sort=request.get_json().get("new_arc_sort")
    if not all([arc_sort,new_arc_sort]):
        current_app.logger.error(LoggerError.PARAMERROR)
        return jsonify(code=RET.PARAMERR, msg="参数错误")
    try:
        arc_sorts=db.session.query(ArticleSort).filter(ArticleSort.sort==arc_sort,ArticleSort.is_del==0).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR, msg="查询数据失败", data="")
    if not arc_sorts:
        current_app.logger.error(LoggerError.NODATA)
        return jsonify(code=RET.NODATA,msg="没有查询到文章数据",data="")
    arc_sorts.sort=new_arc_sort
    try:
        db.session.commit()  # 提交修改
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR, msg="修改文章分类失败", data="")
    return jsonify(code=RET.OK, msg="修改文章分类成功", data="")


#删除文章标签(软删除)
@admin.route("/del_arc_sort",methods=["POST"])
@http_auth.login_required
def del_arc_sort():
    if not g.user_id:
        current_app.logger.error(LoggerError.AUTHERROR)
        return jsonify(code=RET.REQERR,msg="无权请求此接口",data="")
    arc_sort=request.get_json().get("arc_sort")
    if not arc_sort:
        current_app.logger.error(LoggerError.PARAMERROR)
        return jsonify(code=RET.PARAMERR, msg="参数错误")
    try:
        arc_sorts=db.session.query(ArticleSort).filter(ArticleSort.sort==arc_sort,ArticleSort.is_del==0).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR, msg="查询数据失败", data="")
    if not arc_sorts:
        current_app.logger.error(LoggerError.NODATA)
        return jsonify(code=RET.NODATA,msg="没有查询到文章数据",data="")
    try:
        arc_sorts.is_del=1
        db.session.commit()  # 提交修改
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR, msg="删除文章分类失败", data="")
    return jsonify(code=RET.OK, msg="删除文章分类成功", data="")


#删除文章标签类型接口(从数据库删除)
@admin.route("/del_arc_sort_from_deled",methods=["POST"])
@http_auth.login_required
def del_arc_sort_from_deled():
    if not g.user_id:
        current_app.logger.error(LoggerError.AUTHERROR)
        return jsonify(code=RET.REQERR,msg="无权请求此接口",data="")
    arc_sort=request.get_json().get("arc_sort")
    if not arc_sort:
        current_app.logger.error(LoggerError.PARAMERROR)
        return jsonify(code=RET.PARAMERR, msg="参数错误")
    try:
        arc_sorts=db.session.query(ArticleSort).filter(ArticleSort.sort==arc_sort,ArticleSort.is_del==1).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR, msg="查询数据失败", data="")
    if not arc_sorts:
        current_app.logger.error(LoggerError.NODATA)
        return jsonify(code=RET.NODATA,msg="没有查询到文章数据",data="")
    try:
        db.session.delete(arc_sorts)
        db.session.commit()  # 提交修改
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR, msg="删除文章分类失败", data="")
    return jsonify(code=RET.OK, msg="删除文章分类成功", data="")

#显示文章列表
@admin.route("/arcs",methods=["POST"])
@http_auth.login_required
def get_arc():
    if not g.user_id:
        current_app.logger.error(LoggerError.AUTHERROR)
        return jsonify(code=RET.REQERR,msg="无权请求此接口",data="")
    user_id =g.user_id
    try:
        arcs=db.session.query(Article.id,Article.title,Article.addtime,ArticleSort.sort).filter(User.id==user_id,Article.is_del==0,Article.article_sort_id==ArticleSort.id).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR,msg="查询数据失败",data="")
    if not arcs:
        current_app.logger.error(LoggerError.NODATA)
        return jsonify(code=RET.NODATA,msg="没有查询到文章数据",data="")
    arc_data=[{
        "id":arc.id,
        "title":arc.title,
        "sort":arc.sort,
        "addtime":str(arc.addtime)
    } for arc in arcs]
    return jsonify(code=RET.OK,msg="获取文章详情页面成功",data=arc_data)
   
#显示已删除文章列表
@admin.route("/deled_arcs",methods=["POST"])
@http_auth.login_required
def get_deled_arc():
    if not g.user_id:
        current_app.logger.error(LoggerError.AUTHERROR)
        return jsonify(code=RET.REQERR,msg="无权请求此接口",data="")
    user_id =g.user_id
    try:
        arcs=db.session.query(Article.id,Article.title,Article.addtime,ArticleSort.sort).filter(User.id==user_id,Article.is_del==1,Article.article_sort_id==ArticleSort.id).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR,msg="查询数据失败",data="")
    if not arcs:
        current_app.logger.error(LoggerError.NODATA)
        no_arc_data=[]
        return jsonify(code=RET.NODATA,msg="没有查询到文章数据",data=no_arc_data)
    arc_data=[{
        "id":arc.id,
        "title":arc.title,
        "sort":arc.sort,
        "addtime":str(arc.addtime)
    } for arc in arcs]
    return jsonify(code=RET.OK,msg="获取文章详情页面成功",data=arc_data)


#文章预览详情接口
@admin.route("/arc_info",methods=["GET"])
@http_auth.login_required
def get_arc_Info():
    if not g.user_id:
        current_app.logger.error(LoggerError.AUTHERROR)
        return jsonify(code=RET.REQERR,msg="无权请求此接口",data="")
    user_id =g.user_id
    arc_id=request.args.get("aid")
    if not arc_id:
            current_app.logger.error(LoggerError.PARAMERROR)
            return jsonify(code=RET.PARAMERR, msg="参数错误")
    try:
        arc=db.session.query(Article.id,Article.title,ArticleSort.sort,Article.content, Article.addtime).filter(User.id==user_id,Article.is_del==0,Article.id==arc_id,Article.article_sort_id==ArticleSort.id).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR,msg="查询数据失败",data="")
    if not arc:
        current_app.logger.error(LoggerError.NODATA)
        return jsonify(code=RET.NODATA,msg="没有查询到文章数据",data="")
    arc_data={
        "id":arc.id,
        "title":arc.title,
        "sort":arc.sort,
        "addtime":str(arc.addtime),
        "content":arc.content
    }
    return jsonify(code=RET.OK,msg="获取文章详情页面成功",data=arc_data)

#添加文章
@admin.route("/add_arc",methods=["GET","POST"])
@http_auth.login_required
def add_arc():
    req_data=request.get_json()
    arc_sort_id=req_data.get("sort")     #分类
    title=req_data.get("title")   #文章名称
    content=req_data.get("content")   #文章内容
    if not all([title,content,arc_sort_id]):
        current_app.logger.error(LoggerError.PARAMERROR)
        return jsonify(code=RET.PARAMERR,msg="参数错误")
    if not g.user_id:
        current_app.logger.error(LoggerError.AUTHERROR)
        return jsonify(code=RET.REQERR,msg="无权请求此接口",data="")
    user_id =g.user_id
    try:
        arcs=db.session.query(Article).filter(Article.title==title,User.id==user_id).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR,msg="查询数据库错误")
    if arcs is not None:
        if arcs.is_del==1:
            arcs.is_del=0
            return jsonify(code=RET.OK,msg="文章已从数据库恢复")
        current_app.logger.error(LoggerError.DATAEXIST)
        return jsonify(code=RET.DATAEXIST,msg="文章已存在")
    article = Article(
        title=title,
        content=content,
        user_id=user_id,
        article_sort_id=arc_sort_id,
        addtime=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
    try:
        db.session.add(article)
        db.session.commit()   #提交事务
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR,msg="添加文章失败",data="")
    return jsonify(code=RET.OK,msg="添加文章成功",data="")
   

#编辑文章
@admin.route("/change_arc",methods=["GET","POST"])
@http_auth.login_required
def change_arc():
    if not g.user_id:
        current_app.logger.error(LoggerError.AUTHERROR)
        return jsonify(code=RET.REQERR,msg="无权请求此接口",data="")
    user_id =g.user_id
    if request.method=="POST":
        req_data=request.get_json()
        #需要编辑的文章id
        arc_id=req_data.get("aid")
        #需要修改的内容
        arc_sort_id=req_data.get("sort")     #分类
        title=req_data.get("title")   #商品名称
        content=req_data.get("content")   #文章内容
        # print(arc_sort_id)
        if not all([title,content,arc_sort_id]):
            current_app.logger.error(LoggerError.PARAMERROR)
            return jsonify(code=RET.PARAMERR,msg="参数错误")
        try:
            arc=db.session.query(Article).filter(Article.id==arc_id,User.id==user_id).first()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(code=RET.DBERR,msg="查询数据库失败",data="")
        arc.title=title
        arc.article_sort_id=arc_sort_id
        arc.content=content
        try:
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            current_app.logger.error(e)   
            return jsonify(code=RET.DBERR,msg="修改文章失败",data="")
        return jsonify(code=RET.OK,msg="修改文章成功",data="")
    else:
        # 获取需要编辑的文章的详细信息
        # 需要编辑的文章id
        arc_id=request.args.get("aid")
        if not arc_id:
            current_app.logger.error(LoggerError.PARAMERROR)
            return jsonify(code=RET.PARAMERR,msg="参数错误")
        try:
            arc=db.session.query(Article.id,Article.title,Article.content,Article.addtime,Article.article_sort_id).filter(Article.id==arc_id,User.id==user_id).first()
           
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(code=RET.DBERR,msg="查询数据库失败",data="")
        
        if not arc:
            current_app.logger.error(LoggerError.NODATA)
            return jsonify(code=RET.NODATA,msg="没有查询到此文章")
        title=arc.title
        content=arc.content
        sort=arc.article_sort_id
        arc_data={
            "title":title,
            "content":content,
            "sort":sort
        }
        return jsonify(code=RET.OK,msg="获取文章成功",data=arc_data)

#删除文章
@admin.route("/del_arc",methods=["POST"])
@http_auth.login_required
def delete_arc():
    if not g.user_id:
        current_app.logger.error(LoggerError.AUTHERROR)
        return jsonify(code=RET.REQERR,msg="无权请求此接口",data="")
    user_id =g.user_id
    req_data=request.get_json()
    #需要删除的文章id
    arc_id=req_data.get("aid")
    if not arc_id:
        current_app.logger.error(LoggerError.PARAMERROR)
        return jsonify(code=RET.PARAMERR,msg="参数错误")
    try:
        arc = Article.query.filter(Article.id==arc_id,User.id==user_id).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR,msg="查询数据库失败",data="")
    if arc is None:
        current_app.logger.error(LoggerError.NODATA)
        return jsonify(code=RET.NODATA,msg="没有查询到此文章")
    try:
        arc.is_del=1
        db.session.commit()
    except Exception as e:
        db.session.rollback() 
        current_app.logger.error(e)     
        return jsonify(code=RET.DBERR,msg="查询数据库失败",data="")
    return jsonify(code=RET.OK,msg="删除文章成功",data="")

#从回收站删除文章，彻底删除
@admin.route("/del_arc_from_deled",methods=["POST"])
@http_auth.login_required
def delete_arc_from_deled():
    if not g.user_id:
        current_app.logger.error(LoggerError.AUTHERROR)
        return jsonify(code=RET.REQERR,msg="无权请求此接口",data="")
    user_id =g.user_id
    req_data=request.get_json()
    #需要删除的文章id
    arc_id=req_data.get("aid")
    if not arc_id:
        current_app.logger.error(LoggerError.PARAMERROR)
        return jsonify(code=RET.PARAMERR,msg="参数错误")
    try:
        arc = Article.query.filter(Article.id==arc_id,User.id==user_id).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR,msg="查询数据库失败",data="")
    if not arc:
        current_app.logger.error(LoggerError.NODATA)
        return jsonify(code=RET.NODATA,msg="没有查询到此文章")
    try:
        db.session.delete(arc)
        db.session.commit()
    except Exception as e:
        db.session.rollback() 
        current_app.logger.error(e)     
        return jsonify(code=RET.DBERR,msg="查询数据库失败",data="")
    return jsonify(code=RET.OK,msg="删除文章成功",data="")

#回收站文章恢复接口，软删除恢复
@admin.route("/recovery_arc",methods=["POST"])
@http_auth.login_required
def recovery_arc():
    if not g.user_id:
        current_app.logger.error(LoggerError.AUTHERROR)
        return jsonify(code=RET.REQERR,msg="无权请求此接口",data="")
    user_id =g.user_id
    req_data=request.get_json()
    #需要恢复的文章id
    arc_id=req_data.get("aid")
    if not arc_id:
        current_app.logger.error(LoggerError.PARAMERROR)
        return jsonify(code=RET.PARAMERR,msg="参数错误")
    try:
        arc = Article.query.filter(Article.id==arc_id,User.id==user_id).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR,msg="查询数据库失败",data="")
    if arc is None:
        current_app.logger.error(LoggerError.NODATA)
        return jsonify(code=RET.NODATA,msg="没有查询到此文章")
    try:
        arc.is_del=0
        db.session.commit()
    except Exception as e:
        db.session.rollback() 
        current_app.logger.error(e)     
        return jsonify(code=RET.DBERR,msg="查询数据库失败",data="")
  
    return jsonify(code=RET.OK,msg="恢复文章成功",data="")


# 文章评论接口
@admin.route("/arc_comment",methods=["GET","POST"])
@http_auth.login_required
def arc_comment():
        try:
            arc_comments=db.session.query(ArticleComment.id,ArticleComment.nick_name,ArticleComment.comment,ArticleComment.email,ArticleComment.addtime,Article.title).filter(ArticleComment.article_id==Article.id,ArticleComment.is_del==0).all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(code=RET.DBERR,msg="数据库查询失败",data="")
        if not arc_comments:
            current_app.logger.error(LoggerError.NODATA)
            return jsonify(code=RET.NODATA, msg="没有查询到评论数据", data="")
        arc_comment_data = [{
            "id": arc_comment.id,
            "nick_name": arc_comment.nick_name,
            "title":arc_comment.title,
            "comment": arc_comment.comment,
            "email":arc_comment.email,
            "addtime": str(arc_comment.addtime)
        } for arc_comment in arc_comments]
        return jsonify(code=RET.OK,msg="获取文章评论成功",data=arc_comment_data)

# 文章评论回复接口
@admin.route("/reply_comment",methods=["POST"])
@http_auth.login_required
def reply_comment():
        req_data=request.get_json()
        comment_id=req_data.get("comment_id")
        reply_comment=req_data.get("reply_comment")
        is_to_email=req_data.get("to_email")
        # print(comment_id,reply_comment,is_to_email)
        if not all([comment_id,reply_comment]):
            current_app.logger.error(LoggerError.PARAMERROR)
            return jsonify(code=RET.PARAMERR, msg="没有查询到评论数据", data="")
        try:
            arc_comments=db.session.query(ArticleComment).filter(ArticleComment.id==comment_id,ArticleComment.is_del==0).first()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(code=RET.DBERR,msg="数据库查询失败",data="")
        if not arc_comments:
            current_app.logger.error(LoggerError.NODATA)
            return jsonify(code=RET.NODATA, msg="没有查询到评论数据", data="")
        if is_to_email:
            pass
        
        reply_comments=ReplyComment(
            reply_comment=reply_comment,
            comment_id=comment_id
        )
        try:
            db.session.add(reply_comments)
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(code=RET.DBERR, msg="查询数据库错误", data="")
        return jsonify(code=RET.OK,msg="回复文章评论成功")

# 文章评论删除接口
@admin.route("/del_comment",methods=["POST"])
@http_auth.login_required
def del_comment():
    comment_id=request.get_json().get("comment_id")
    if not comment_id:
        current_app.logger.error(LoggerError.PARAMERROR)
        return jsonify(code=RET.PARAMERR, msg="没有查询到评论数据", data="")
    try:
        arc_comment=db.session.query(ArticleComment).filter(ArticleComment.id==comment_id,ArticleComment.is_del==0).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR,msg="数据库查询失败",data="")
    if not arc_comment:
        current_app.logger.error(LoggerError.NODATA)
        return jsonify(code=RET.NODATA, msg="没有查询到评论数据", data="")
    try:
        arc_comment.is_del=1
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR, msg="删除评论失败", data="")
    return jsonify(code=RET.OK,msg="删除文章评论成功")